package com.chn.hourent.service;

import com.chn.hourent.model.House;

public class HouseService {//核心功能区，主要算法都写在此处
    private House[] houses;//用数组保存House对象
    private int houseNum = 1;
    //记录当前有多少个房屋信息,列表中初始含有一个houses[0]，所以houseNum从1开始

    public HouseService(int size) {
        houses = new House[size];//创建HouseService对象时，指定创建的数组长度
        houses[0] = new House(1, "万叶", "191277", "郑州工业应用技术学院", 3000, "未租出");
    }

    public House findById(int findId) {
        for (int i = 0; i < houseNum; i++) {
            if (findId == houses[i].getId())
                return houses[i];
        }
        return null;
    }
    //┏━━━━━━━━━━━━━━━━━━━━━━━━━腾达写的━━━━━━━━━━━━━━━━━━━━━━━━━┓
    public boolean del(int delId) {
        for (int i = 0; i < houseNum; i++) {
            if (delId == houses[i].getId()) {
                if(delId == houses.length) {//如果删除最后一个，则直接将其变为null
                    houses[delId - 1] = null;
                    return true;
                }
                for (; i < houseNum - 1; i++) {
                    houses[i] = houses[i + 1];
                    houses[i].setId((houses[i].getId()-1));
                }
                houses[--houseNum] = null;
                return true;
            }
        }
        return false;
    }
    //┏━━━━━━━━━━━━━━━━━━━━━━━━━我写的━━━━━━━━━━━━━━━━━━━━━━━━━┓
//    public boolean del(int delId) {
//        for (int i = 0; i < houseNum; i++) {
//            if (delId == houses[i].getId()) {
//                for (; i < houseNum; i++) {//好像i < houseNum可以替换掉下面这句
////                if ((i + 1)!=houses.length) {
//                    houses[i] = houses[i + 1];
////                  houses[i].setId((houses[i].getId()-1));
////                }
//                }
//                houses[--houseNum] = null;
//                return true;
//            }
//        }
//        return false;
//    }
    //┏━━━━━━━━━━━━━━━━━━━━━━━━━老师写的━━━━━━━━━━━━━━━━━━━━━━━━━┓
//    public boolean del1(int delId){
//        int index=-1;
//        for (int i = 0; i < houseNum; i++) {
//            if (delId==houses[i].getId()){
//                index=i;
//            }
//        }
//        if (index==-1){
//            return false;
//        }
//        for (int i = index; i <houseNum-1 ; i++) {
//            houses[i]=houses[i+1];
//        }
//        houses[--houseNum]=null;
//        return true;
//    }

    public boolean add(House newHouse) {//add方法，创建新对象
        if (houseNum >= houses.length) {//判断数组是否已装满
            return false;
        }
        newHouse.setId(houseNum + 1);//用houseNum替换掉newHouse中的占位id:"0"
        houses[houseNum++] = newHouse;//因为初始的houses[0]已存在，所以添加的第一个就是houses[1],并自加
        return true;
    }

    public House[] list() {
        return houses;
    }
}
